import re
import csv
import argparse
from pathlib import Path

def parse_bookmark_file(file_path):
    """解析书签文件，返回书签列表"""
    with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
        content = f.read()
    
    # 检查文件类型
    if 'Firefox' in content:
        file_type = 'firefox'
    elif 'Chrome' in content:
        file_type = 'chrome'
    else:
        file_type = 'unknown'
    
    # 提取所有文件夹和书签
    folders = []
    current_path = []
    
    # 处理文件夹开始标签
    folder_pattern = re.compile(r'<DT><H3(?:.*?)>(.*?)</H3>')
    folder_start_pattern = re.compile(r'<DL><p>')
    folder_end_pattern = re.compile(r'</DL><p>')
    
    # 处理书签条目
    bookmark_pattern = re.compile(
        r'<DT><A HREF="(.*?)"(?:.*?)>(.*?)</A>(?:.*?)(?:<DD>(.*?))?$', 
        re.DOTALL
    )
    
    lines = content.split('\n')
    bookmarks = []
    
    for line in lines:
        # 检查文件夹开始
        folder_match = folder_pattern.search(line)
        if folder_match:
            folder_name = folder_match.group(1)
            current_path.append(folder_name)
            folders.append({
                'name': folder_name,
                'path': list(current_path)
            })
        
        # 检查文件夹结束
        if folder_end_pattern.search(line):
            if current_path:
                current_path.pop()
        
        # 检查书签
        bookmark_match = bookmark_pattern.search(line)
        if bookmark_match:
            url = bookmark_match.group(1)
            name = bookmark_match.group(2)
            # 书签描述可能不存在
            description = bookmark_match.group(3) if bookmark_match.group(3) else ''
            
            # 获取当前文件夹路径
            folder_path = " > ".join(current_path) if current_path else "根目录"
            
            bookmarks.append({
                'url': url,
                'name': name,
                'description': description,
                'folder_path': folder_path
            })
    
    return bookmarks, file_type

def main():
    """主函数，处理命令行参数并执行解析"""
    parser = argparse.ArgumentParser(description='解析Firefox和Chrome导出的书签文件')
    parser.add_argument('input_file', help='书签文件路径')
    parser.add_argument('-o', '--output', help='输出CSV文件路径', default='bookmarks.csv')
    
    args = parser.parse_args()
    
    input_path = Path(args.input_file)
    output_path = Path(args.output)
    
    if not input_path.exists():
        print(f"错误：文件 '{input_path}' 不存在")
        return
    
    try:
        bookmarks, file_type = parse_bookmark_file(input_path)
        print(f"成功解析 {file_type} 书签文件，共找到 {len(bookmarks)} 个书签")
        
        # 写入CSV文件
        with open(output_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
            fieldnames = ['名称', 'URL', '书签目录', '描述']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            
            writer.writeheader()
            for bookmark in bookmarks:
                writer.writerow({
                    '名称': bookmark['name'],
                    'URL': bookmark['url'],
                    '书签目录': bookmark['folder_path'],
                    '描述': bookmark['description']
                })
        
        print(f"书签已成功导出到 '{output_path}'")
        
    except Exception as e:
        print(f"解析过程中发生错误: {e}")

if __name__ == "__main__":
    main()